package 字符串解码394;

import java.util.ArrayDeque;

/**
 * @author 谢阳
 * @version 1.8.0_131
 */
class Solution {
    public static void main(String[] args) {
        String str = "2[abc]3[cd]ef";
        String s = decodeString(str);
        System.out.println(s);
    }

    public static String decodeString(String s) {
        int len = s.length();
        StringBuilder res = new StringBuilder();
        ArrayDeque<String> strDeque = new ArrayDeque<>();
        ArrayDeque<Integer> numDeque = new ArrayDeque<>();
        int i = 0;
        int j = 0;
        while (j < len) {

            while (Character.isDigit(s.charAt(j))) {
                j++;
            }

            if (i != j) {
                numDeque.push(Integer.parseInt(s.substring(i, j)));
                i = j;
            }

            if ('[' == s.charAt(j)) {
                j++;
                strDeque.push(s.substring(i, j));
                i = j;
            }

            while (j < len && Character.isAlphabetic(s.charAt(j))) {
                j++;
            }

            if (i != j){
                if (strDeque.isEmpty()) {
                    res.append(s, i, j);
                } else {
                    if (strDeque.peek().equals("[")) {
                        strDeque.push(s.substring(i, j));
                    } else {
                        strDeque.push(strDeque.pop() + s.substring(i, j));
                    }
                }
                i = j;
            }

            if (j < len && ']' == s.charAt(j)) {
                j++;
                i = j;
                StringBuilder temp = new StringBuilder();
                for (int k = 0; k < numDeque.peek(); k++) {
                    temp.append(strDeque.peek());
                }
                strDeque.pop();
                strDeque.pop();
                numDeque.pop();

                if (strDeque.isEmpty()) {
                    res.append(temp);
                } else {
                    if (strDeque.peek().equals("[")) {
                        strDeque.push(temp.toString());
                    } else {
                        strDeque.push(strDeque.pop() + temp.toString());
                    }
                }
            }
        }
        return res.toString();

    }


}




